﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Web.Mvc;

namespace Web.Infrastructure.Mvc.MvcCaptcha
{
    public class CaptchaModel : IValidatableObject
    {
        public CaptchaModel()
        {
            this.CaptchaName = Guid.NewGuid().ToString().Replace("-", "");
        }

        [Required]
        [Display(Name = "验证码")]
        [UIHint("Captcha")]
        public string Captcha { get; set; }

        [Required]
        [HiddenInput(DisplayValue = false)]
        public string CaptchaName { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (string.IsNullOrEmpty(this.CaptchaName))
            {
                yield return new ValidationResult("验证码丢失", new List<string> { "Captcha" });
            }
            else
            {
                var cookie = HttpContext.Current.Request.Cookies[this.CaptchaName];
                if (cookie == null || string.IsNullOrEmpty(cookie.Value))
                {
                    yield return new ValidationResult("验证码丢失", new List<string> { "Captcha" });
                }
                else
                {
                    string captchCode = cookie.Value;
                    if (this.Captcha.Hash() != captchCode)
                    {
                        yield return new ValidationResult("验证码错误", new List<string> { "Captcha" });
                    }
                    else
                    {
                        HttpContext.Current.Response.Cookies.Remove(this.CaptchaName);
                    }
                }
            }
        }
    }
}